/**
 * PCM音频播放器
 * 用于播放通义千问TTS返回的PCM格式音频
 */
export class PCMAudioPlayer {
  constructor(sampleRate = 24000) {
    this.sampleRate = sampleRate
    this.audioContext = null
    this.audioQueue = []
    this.isPlaying = false
    this.currentSource = null
    this.onPlaybackEnd = null
    this.analyser = null
  }

  /**
   * 获取分析器节点
   */
  getAnalyser() {
    this.init()
    if (!this.analyser) {
      this.analyser = this.audioContext.createAnalyser()
      this.analyser.fftSize = 256
    }
    return this.analyser
  }

  /**
   * 初始化AudioContext
   */
  init() {
    if (!this.audioContext) {
      this.audioContext = new (window.AudioContext || window.webkitAudioContext)()
    }
  }

  /**
   * 将base64编码的PCM数据转换为AudioBuffer
   * @param {string} base64Audio - base64编码的PCM音频数据
   * @returns {AudioBuffer}
   */
  async base64ToAudioBuffer(base64Audio) {
    this.init()

    // 解码base64
    const binaryString = atob(base64Audio)
    const bytes = new Uint8Array(binaryString.length)
    for (let i = 0; i < binaryString.length; i++) {
      bytes[i] = binaryString.charCodeAt(i)
    }

    // 将PCM 16-bit转换为Float32Array
    const int16Array = new Int16Array(bytes.buffer)
    const float32Array = new Float32Array(int16Array.length)
    
    for (let i = 0; i < int16Array.length; i++) {
      // 将16-bit整数转换为[-1, 1]范围的浮点数
      float32Array[i] = int16Array[i] / 32768.0
    }

    // 创建AudioBuffer
    const audioBuffer = this.audioContext.createBuffer(
      1, // 单声道
      float32Array.length,
      this.sampleRate
    )

    // 填充数据
    audioBuffer.getChannelData(0).set(float32Array)

    return audioBuffer
  }

  /**
   * 添加音频数据到播放队列
   * @param {string} base64Audio - base64编码的PCM音频数据
   */
  async addAudio(base64Audio) {
    if (!base64Audio) return

    try {
      const audioBuffer = await this.base64ToAudioBuffer(base64Audio)
      this.audioQueue.push(audioBuffer)
      
      // 如果当前没有播放,开始播放
      if (!this.isPlaying) {
        this.playNext()
      }
    } catch (error) {
      console.error('添加音频失败:', error)
    }
  }

  /**
   * 播放队列中的下一个音频
   */
  playNext() {
    if (this.audioQueue.length === 0) {
      this.isPlaying = false
      if (this.onPlaybackEnd) {
        this.onPlaybackEnd()
      }
      return
    }

    this.isPlaying = true
    const audioBuffer = this.audioQueue.shift()

    // 创建音频源
    const source = this.audioContext.createBufferSource()
    source.buffer = audioBuffer

    // 连接音频节点：source -> (analyser) -> destination
    if (this.analyser) {
      source.connect(this.analyser)
      this.analyser.connect(this.audioContext.destination)
    } else {
      source.connect(this.audioContext.destination)
    }

    // 播放结束后播放下一个
    source.onended = () => {
      this.currentSource = null
      this.playNext()
    }

    this.currentSource = source
    source.start(0)
  }

  /**
   * 停止播放
   */
  stop() {
    if (this.currentSource) {
      try {
        this.currentSource.stop()
        this.currentSource = null
      } catch (e) {
        // 忽略已经停止的错误
      }
    }
    this.audioQueue = []
    this.isPlaying = false
  }

  /**
   * 暂停播放
   */
  pause() {
    if (this.audioContext && this.audioContext.state === 'running') {
      this.audioContext.suspend()
    }
  }

  /**
   * 恢复播放
   */
  resume() {
    if (this.audioContext && this.audioContext.state === 'suspended') {
      this.audioContext.resume()
    }
  }

  /**
   * 获取当前播放状态
   */
  getState() {
    return {
      isPlaying: this.isPlaying,
      queueLength: this.audioQueue.length,
      contextState: this.audioContext ? this.audioContext.state : 'closed'
    }
  }

  /**
   * 销毁播放器
   */
  destroy() {
    this.stop()
    if (this.audioContext) {
      this.audioContext.close()
      this.audioContext = null
    }
  }
}

/**
 * 创建全局音频播放器实例
 */
let globalPlayer = null

export function getGlobalPlayer() {
  if (!globalPlayer) {
    globalPlayer = new PCMAudioPlayer(24000)
  }
  return globalPlayer
}

export function destroyGlobalPlayer() {
  if (globalPlayer) {
    globalPlayer.destroy()
    globalPlayer = null
  }
}
